import { HttpException, Injectable } from '@nestjs/common';
import { Unit, Prisma } from '@prisma/client';
import { PrismaService } from 'src/db/prisma.service';
import { requestPromise } from 'src/interface';

@Injectable()
export class UnitsService {
  constructor(private prisma: PrismaService) {}

  async findOne(
    unitWhereUniqueInput: Prisma.UnitWhereUniqueInput,
  ): Promise< any | null> {
    return this.prisma.unit.findUnique({
      where: {
        id: +unitWhereUniqueInput.id,
      },
      select: {
        name: true,
        id: true,
        createAt: true,
        Good:{
          select:{
            id: true,
          }
        }
      }
    });
  }

  async findAll(params: {
    pageNum?: number;
    pageSize?: number;
    cursor?: Prisma.UnitWhereUniqueInput;
    name?: string;
    orderBy?: Prisma.UnitOrderByWithRelationInput;
  }): Promise<requestPromise> {
    const { pageNum = 1, pageSize = 10, cursor, name, orderBy } = params;
    console.log(params, 'params');
    const totalUsersCount = await this.prisma.unit.count({
      where: {
        name: {
          contains: name,
        },
      },
    });
    const goods = await this.prisma.unit.findMany({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      cursor,
      where: {
        name: {
          contains: name,
        },
      },
      orderBy,
    });
    return {
      code: 200,
      message: 'success',
      data: {
        list: goods,
        total: totalUsersCount,
      },
    };
  }

  async create(data: Prisma.UnitCreateInput): Promise<Unit> {
    try {
      let result = await this.prisma.unit.create({
        data,
      });
      return result;
    } catch (e) {
      if (e.meta.target.includes('Unit_name_key')) {
        throw new HttpException('单位名称已存在', 400);
      }
    }
  }

  async update(params: {
    where: Prisma.UnitWhereUniqueInput;
    data: Prisma.UnitUpdateInput;
  }): Promise<Unit> {
    const { where, data } = params;
    return this.prisma.unit.update({
      data,
      where,
    });
  }

  async delete(where: Prisma.UnitWhereUniqueInput): Promise<Unit> {
    return this.prisma.unit.delete({
      where: {
        id: +where.id,
      },
    });
  }
}
